<template>
  <BaseLayout>
    <template #content>
      <div class="search-block">
        <el-form
          :inline="true"
          :model="queryParams"
        >
          <el-row style="gap: 10px">
            <el-col :span="3">
              <el-input
                v-model="queryParams.username"
                placeholder="用户账号"
                :suffix-icon="queryParams.username ? '' : Search"
                clearable
                size="large"
              />
            </el-col>

            <el-col :span="3">
              <el-input
                v-model="queryParams.nickname"
                placeholder="用户昵称"
                :suffix-icon="queryParams.nickname ? '' : Search"
                clearable
                size="large"
              />
            </el-col>

            <el-col :span="3">
              <el-input
                v-model="queryParams.mobile"
                placeholder="手机号码"
                :suffix-icon="queryParams.mobile ? '' : Search"
                clearable
                size="large"
              />
            </el-col>

            <el-col :span="3">
              <el-input
                v-model="queryParams.email"
                placeholder="邮箱"
                :suffix-icon="queryParams.email ? '' : Search"
                clearable
                size="large"
              />
            </el-col>

            <el-col :span="3">
              <el-select
                v-model="queryParams.status"
                placeholder="帐号状态"
                clearable
                size="large"
              >
                <el-option
                  v-for="item in accountStatusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-col>

            <el-col :span="7">
              <el-date-picker
                v-model="queryParams.loginDate"
                type="daterange"
                value-format="YYYY-MM-DD"
                range-separator="-"
                start-placeholder="开始登录日期"
                end-placeholder="结束登录日期"
                clearable
                size="large"
              />
            </el-col>

            <el-col :span="7">
              <el-date-picker
                v-model="queryParams.createTime"
                type="daterange"
                value-format="YYYY-MM-DD"
                range-separator="-"
                start-placeholder="开始创建日期"
                end-placeholder="结束创建日期"
                clearable
                size="large"
              />
            </el-col>

            <el-col
              :span="8"
              class="button-group"
            >
              <el-button
                type="primary"
                size="large"
                @click="getTableData"
              >
                搜索
              </el-button>

              <el-button
                type="warning"
                size="large"
                @click="handleResetSearchForm"
              >
                重置
              </el-button>
            </el-col>

            <el-col
              :span="8"
              class="add-button"
            >
              <el-button
                type="success"
                size="large"
                @click="handleAdd"
              >
                新增用户
              </el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <el-table
        border
        v-loading="tableLoading"
        :data="tableData"
        :stripe="true"
        :header-cell-style="() => ({ background: '#F8F8F8' })"
      >
        <el-table-column
          prop="id"
          label="用户编号"
          min-width="150"
          align="center"
        />

        <el-table-column
          prop="username"
          label="用户账号"
          min-width="150"
          align="center"
        />

        <el-table-column
          prop="nickname"
          label="用户昵称"
          min-width="150"
          align="center"
        />

        <el-table-column
          prop="email"
          label="用户邮箱"
          min-width="150"
          align="center"
        />

        <el-table-column
          prop="mobile"
          label="手机号码"
          min-width="150"
          align="center"
        />

        <el-table-column
          label="状态"
          min-width="150"
          align="center"
        >
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-text="启用"
              inactive-text="禁用"
              :active-value="0"
              :inactive-value="1"
              @click="handleStatusChange(scope.row)"
              style="--el-switch-on-color: #13ce66"
            />
          </template>
        </el-table-column>

        <el-table-column
          prop="loginDate"
          label="最后登录时间"
          min-width="180"
          align="center"
        >
          <template #default="scope">
            {{ formatTime(scope.row.loginDate) }}
          </template>
        </el-table-column>

        <el-table-column
          prop="createTime"
          label="创建时间"
          min-width="180"
          align="center"
        >
          <template #default="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column
          fixed="right"
          label="操作"
          width="250"
          align="center"
        >
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              plain
              link
              @click="handleDetail(scope.row.id)"
            >
              详情
            </el-button>

            <el-button
              type="primary"
              size="small"
              plain
              link
              @click="handleEdit(scope.row.id)"
            >
              编辑
            </el-button>

            <el-button
              type="primary"
              size="small"
              plain
              link
              @click="handleRoleAssign(scope.row.id)"
            >
              角色分配
            </el-button>

            <el-button
              type="danger"
              size="small"
              plain
              link
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <UserFormDialog
        v-model="isFormDialogVisible"
        :isEdit="isEdit"
        :userId="formUserId"
        @update="getTableData"
      />

      <UserDetailDialog
        v-model="isDetailDialogVisible"
        :userId="detailDialogUserId"
      />

      <RoleAssignDialog
        v-model="isRoleAssignDialogVisible"
        :userId="roleAssignDialogUserId"
      />
    </template>

    <template #footer>
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="handlePagination"
      />
    </template>
  </BaseLayout>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { deleteUser, getUserPage, updateUserStatus } from '@/api/user'
import { defaultPage, defaultPageSize } from '@/types/api.d'
import { accountStatusOptions, genderOptions } from '@/utils/globalOptions'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { showDangerMessageBox } from '@/utils/messageUtil'
import dayjs from 'dayjs'
import UserFormDialog from './components/userFormDialog/index.vue'
import UserDetailDialog from './components/userDetailDialog/index.vue'
import RoleAssignDialog from './components/roleAssignDialog/index.vue'

/**
 * 表格属性
 */
const tableData = ref([])
const tableLoading = ref(true)

/**
 * 分页器属性
 */
const total = ref(0)

/**
 * 详情对话框
 */
const isDetailDialogVisible = ref(false)
const detailDialogUserId = ref()

/**
 * 新增/编辑对话框
 */
const isFormDialogVisible = ref(false)
const formUserId = ref()
const isEdit = ref(false)

/**
 * 角色分配对话框
 */
const isRoleAssignDialogVisible = ref(false)
const roleAssignDialogUserId = ref()

const queryParams = reactive({
  username: '', // 用户账号
  mobile: '', // 手机号码
  nickname: '', // 用户昵称
  email: '', // 邮箱
  status: '', // 展示状态
  loginDate: [], // 最后一次登录时间
  createTime: [], // 创建时间
  pageNo: defaultPage, // 当前页码
  pageSize: defaultPageSize // 每页显示数量
})

onMounted(async () => {
  await getTableData()
})

/**
 * 获取表格数据
 */
const getTableData = async () => {
  tableLoading.value = true
  const res = await getUserPage(queryParams)

  if (res) {
    tableData.value = res.list
    total.value = res.total
    tableLoading.value = false
  }
}

/**
 * 分页事件
 */
const handlePagination = async ({ page, limit }: { page: number; limit: number }) => {
  queryParams.pageNo = page
  queryParams.pageSize = limit
  await getTableData()
}

/**
 * 帐号状态
 */
const formatAccountStatus = (value: number | any) => {
  return accountStatusOptions.find(item => item.value == value)?.label
}

/**
 * 时间格式化
 */
const formatTime = (time: number | any) => {
  if (!time) {
    return '-'
  }

  return typeof time === 'number' ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '-'
}

/**
 * 重置搜索表单
 */
const handleResetSearchForm = async () => {
  Object.assign(queryParams, {
    username: '',
    mobile: '',
    nickname: '',
    email: '',
    status: '',
    loginDate: '',
    createTime: '',
    pageNo: defaultPage,
    pageSize: defaultPageSize
  })
  await getTableData()
}

/**
 * 新增用户
 */
const handleAdd = () => {
  isEdit.value = false
  isFormDialogVisible.value = true
}

/**
 * 查看详情
 */
const handleDetail = (id: number) => {
  detailDialogUserId.value = id
  isDetailDialogVisible.value = true
}

/**
 * 编辑用户
 */
const handleEdit = (id: number) => {
  isEdit.value = true
  formUserId.value = id
  isFormDialogVisible.value = true
}

/**
 * 角色分配
 */
const handleRoleAssign = (id: number) => {
  roleAssignDialogUserId.value = id
  isRoleAssignDialogVisible.value = true
}

/**
 * 删除用户
 */
const handleDelete = (id: number) => {
  showDangerMessageBox('警告', '确定要该用户删除吗？', async () => {
    await deleteUser({ id: id })
    ElMessage.success('删除成功')
    await getTableData()
  })
}

/**
 * 修改用户状态
 */
const handleStatusChange = async (row: any) => {
  await updateUserStatus({
    id: row.id,
    status: row.status
  })
}
</script>

<style scoped lang="scss">
.search-block {
  margin-bottom: 20px;
}

.button-group {
  display: flex;
  justify-content: flex-start;
}

.add-button {
  display: flex;
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .button-group,
  .add-button {
    flex-wrap: wrap;
    justify-content: center;
  }
}
</style>
